// materials.js
// 物资分析看板核心交互与图表渲染脚本
// 主要功能：模态框穿透、图表渲染入口、静态数据结构示例
// 所有内容均有中文注释，便于理解和维护

// =====================
// 1. 图表实例管理（避免重复创建）
// =====================
const chartInstances = {};

// 销毁指定canvas的Chart实例
function destroyChart(canvasId) {
    if (chartInstances[canvasId]) {
        chartInstances[canvasId].destroy();
        delete chartInstances[canvasId];
    }
}

// 创建Chart实例并保存引用
function createChart(canvasId, config) {
    // 先销毁已存在的实例
    destroyChart(canvasId);
    // 创建新实例并保存
    chartInstances[canvasId] = new Chart(document.getElementById(canvasId), config);
    return chartInstances[canvasId];
}

// =====================
// 2. 模态框穿透查询逻辑
// =====================
const modal = document.getElementById('detailModal');
const modalTitle = document.getElementById('modalTitle');
const modalContent = document.getElementById('modalContent');
const closeModal = document.getElementById('closeModal');
const closeModalBtn = document.getElementById('closeModalBtn');

// 打开模态框，type为指标标识
window.showDetail = function (type) {
    modal.classList.remove('hidden');
    // 根据type填充不同内容
    renderModalContent(type);
};

closeModal.onclick = closeModalBtn.onclick = function () {
    modal.classList.add('hidden');
};

// =====================
// 3. 模态内容渲染（全覆盖）
// =====================
function renderModalContent(type) {
    // 这里只做结构演示，实际可根据type加载不同图表/表格
    let title = '';
    let html = '';
    switch (type) {
        // 计划管理
        case 'planAchievement':
            title = '采购计划达成率 - 年度趋势与TOP5分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>指标解读</b><br>
                    采购计划达成率反映了当期采购计划完成程度，同比对比揭示计划执行趋势，衡量计划与实际的匹配度。达成率低可能表明采购执行能力不足或计划制定不合理，需结合计划准确率分析是执行问题还是计划问题。
                </div>
                <div class="flex flex-col md:flex-row gap-4 items-stretch">
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">年度趋势</h4>
                        <canvas id="modalPlanAchievementChart" height="120"></canvas>
                    </div>
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">计划达成率TOP5</h4>
                        <canvas id="modalPlanAchievementTop5Chart" height="120"></canvas>
                    </div>
                </div>
            `;
            setTimeout(() => {
                // 年度趋势曲线图（平滑）
                createChart('modalPlanAchievementChart', {
                    type: 'line',
                    data: {
                        labels: ['2019', '2020', '2021', '2022', '2023'],
                        datasets: [{
                            label: '计划达成率',
                            data: [88, 90, 92, 94, 94.2],
                            borderColor: '#165DFF',
                            backgroundColor: 'rgba(22,93,255,0.1)',
                            fill: true,
                            tension: 0.4 // 平滑曲线
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { display: true } },
                        scales: {
                            x: { grid: { display: false }, ticks: { color: '#86909C' }, title: { display: true, text: '年份' } },
                            y: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { color: '#86909C' }, title: { display: true, text: '达成率(%)' } }
                        }
                    }
                });
                // 水平条形图，按数值从大到小排列
                const top5Labels = ['原材料', '零部件', '设备', '辅料', '包装物'];
                const top5Data = [96.8, 95.2, 93.5, 91.8, 89.5];
                createChart('modalPlanAchievementTop5Chart', {
                    type: 'bar',
                    data: {
                        labels: top5Labels,
                        datasets: [{
                            label: '计划达成率(%)',
                            data: top5Data,
                            backgroundColor: '#0FC6C2'
                        }]
                    },
                    options: {
                        indexAxis: 'y', // 水平
                        responsive: true,
                        plugins: { legend: { display: false } },
                        scales: {
                            x: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { color: '#86909C' }, title: { display: true, text: '达成率(%)' } },
                            y: { grid: { display: false }, ticks: { color: '#86909C' }, title: { display: true, text: '物资类别' } }
                        }
                    }
                });
            }, 100);
            break;
        case 'planAccuracy':
            title = '采购计划准确率 - 趋势分析';
            html = `<canvas id="modalPlanAccuracyChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPlanAccuracyChart', '采购计划准确率', [82, 84, 85, 86, 87.5]), 100);
            break;
        case 'unplannedRatio':
            title = '计划外采购占比 - 趋势分析';
            html = `<canvas id="modalUnplannedRatioChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalUnplannedRatioChart', '计划外采购占比', [18, 16, 14, 13, 12.5]), 100);
            break;
        case 'planEfficiency':
            title = '计划执行效率 - 趋势分析';
            html = `<canvas id="modalPlanEfficiencyChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPlanEfficiencyChart', '计划执行效率', [85, 87, 89, 90, 91.8]), 100);
            break;
        // 采购执行
        case 'orderCompletion':
            title = '采购订单完成率 - 趋势分析';
            html = `<canvas id="modalOrderCompletionChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalOrderCompletionChart', '采购订单完成率', [92, 93, 94, 95, 96.8]), 100);
            break;
        case 'supplyTimeliness':
            title = '供给及时率 - 趋势分析';
            html = `<canvas id="modalSupplyTimelinessChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalSupplyTimelinessChart', '供给及时率', [88, 90, 91, 92, 93.2]), 100);
            break;
        case 'qualityRate':
            title = '采购质量合格率 - 趋势分析';
            html = `<canvas id="modalQualityRateChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalQualityRateChart', '采购质量合格率', [96, 97, 97.5, 98, 98.7]), 100);
            break;
        case 'costAchievement':
            title = '采购成本达成率 - 趋势分析';
            html = `<canvas id="modalCostAchievementChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalCostAchievementChart', '采购成本达成率', [90, 92, 93, 94, 95.4]), 100);
            break;
        case 'arrivalCycle':
            title = '移动平均到货周期 - 趋势分析';
            html = `<canvas id="modalArrivalCycleChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalArrivalCycleChart', '移动平均到货周期', [18, 17, 16.5, 16, 15.5]), 100);
            break;
        case 'warehouseCycle':
            title = '移动平均入库周期 - 趋势分析';
            html = `<canvas id="modalWarehouseCycleChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalWarehouseCycleChart', '移动平均入库周期', [3.5, 3.2, 3.0, 2.9, 2.8]), 100);
            break;
        case 'inventoryTime':
            title = '移动平均库存时间 - 趋势分析';
            html = `<canvas id="modalInventoryTimeChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalInventoryTimeChart', '移动平均库存时间', [35, 33, 31, 30, 28.5]), 100);
            break;
        case 'purchaseEfficiency':
            title = '采购效率指数 - 趋势分析';
            html = `<canvas id="modalPurchaseEfficiencyChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPurchaseEfficiencyChart', '采购效率指数', [85, 87, 89, 91, 92.6]), 100);
            break;
        // 库存运营
        case 'inventoryAmount':
            title = '库存总金额 - 趋势分析';
            html = `<canvas id="modalInventoryAmountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalInventoryAmountChart', '库存总金额', [1050, 1120, 1180, 1230, 1280]), 100);
            break;
        case 'inventoryTurnover':
            title = '库存周转率 - 趋势分析';
            html = `<canvas id="modalInventoryTurnoverChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalInventoryTurnoverChart', '库存周转率', [7.2, 7.5, 7.8, 8.2, 8.5]), 100);
            break;
        case 'inventoryCostRate':
            title = '库存持有成本率 - 趋势分析';
            html = `<canvas id="modalInventoryCostRateChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalInventoryCostRateChart', '库存持有成本率', [4.2, 3.8, 3.5, 3.3, 3.2]), 100);
            break;
        case 'stagnantRatio':
            title = '呆滞库存占比 - 趋势分析';
            html = `<canvas id="modalStagnantRatioChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalStagnantRatioChart', '呆滞库存占比', [12.5, 11.8, 10.5, 9.2, 8.7]), 100);
            break;
        // 金额流转
        case 'demandAmount':
            title = '需求总金额 - 趋势分析';
            html = `<canvas id="modalDemandAmountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalDemandAmountChart', '需求总金额', [1250, 1320, 1410, 1480, 1520]), 100);
            break;
        case 'purchaseAmount':
            title = '采购总金额 - 趋势分析';
            html = `<canvas id="modalPurchaseAmountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPurchaseAmountChart', '采购总金额', [1210, 1280, 1350, 1420, 1480]), 100);
            break;
        case 'arrivalAmount':
            title = '到货总金额 - 趋势分析';
            html = `<canvas id="modalArrivalAmountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalArrivalAmountChart', '到货总金额', [1180, 1250, 1320, 1380, 1420]), 100);
            break;
        case 'warehouseAmount':
            title = '入库总金额 - 趋势分析';
            html = `<canvas id="modalWarehouseAmountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalWarehouseAmountChart', '入库总金额', [1150, 1220, 1290, 1350, 1390]), 100);
            break;
        case 'avgOrderAmount':
            title = '均单金额 - 趋势分析';
            html = `<canvas id="modalAvgOrderAmountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalAvgOrderAmountChart', '均单金额', [120, 130, 140, 150, 156]), 100);
            break;
        case 'avgSupplierAmount':
            title = '均企金额 - 趋势分析';
            html = `<canvas id="modalAvgSupplierAmountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalAvgSupplierAmountChart', '均企金额', [250, 265, 280, 290, 298]), 100);
            break;
        case 'purchaseRevenueRatio':
            title = '采购占收入比 - 趋势分析';
            html = `<canvas id="modalPurchaseRevenueRatioChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPurchaseRevenueRatioChart', '采购占收入比', [70.2, 68.5, 67.2, 66.5, 65.8]), 100);
            break;
        case 'purchaseOutputRatio':
            title = '采购占产值比 - 趋势分析';
            html = `<canvas id="modalPurchaseOutputRatioChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPurchaseOutputRatioChart', '采购占产值比', [62.5, 61.2, 60.1, 59.2, 58.2]), 100);
            break;
        // 物料品类
        case 'materialTypes':
            title = '物料种数 - 趋势分析';
            html = `<canvas id="modalMaterialTypesChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalMaterialTypesChart', '物料种数', [1100, 1150, 1200, 1230, 1256]), 100);
            break;
        case 'newMaterialTypes':
            title = '新增物料种数 - 趋势分析';
            html = `<canvas id="modalNewMaterialTypesChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalNewMaterialTypesChart', '新增物料种数', [65, 72, 78, 85, 89]), 100);
            break;
        case 'materialStandardization':
            title = '物料标准化率 - 趋势分析';
            html = `<canvas id="modalMaterialStandardizationChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalMaterialStandardizationChart', '物料标准化率', [70, 72, 74, 76, 78.5]), 100);
            break;
        case 'materialEfficiency':
            title = '品类管理效率 - 趋势分析';
            html = `<canvas id="modalMaterialEfficiencyChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalMaterialEfficiencyChart', '品类管理效率', [78, 80, 82, 84, 85.2]), 100);
            break;
        // 供应商管理
        case 'supplierCount':
            title = '供应商数量 - 趋势分析';
            html = `<canvas id="modalSupplierCountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalSupplierCountChart', '供应商数量', [420, 440, 460, 475, 486]), 100);
            break;
        case 'newSupplierCount':
            title = '新增供应商数量 - 趋势分析';
            html = `<canvas id="modalNewSupplierCountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalNewSupplierCountChart', '新增供应商数量', [25, 28, 30, 31, 32]), 100);
            break;
        case 'singleSourceRatio':
            title = '单一来源采购占比 - 趋势分析';
            html = `<canvas id="modalSingleSourceRatioChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalSingleSourceRatioChart', '单一来源采购占比', [22.5, 21.8, 20.5, 19.2, 18.5]), 100);
            break;
        case 'supplierRisk':
            title = '高风险供应商数量 - 趋势分析';
            html = `<canvas id="modalSupplierRiskChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalSupplierRiskChart', '高风险供应商数量', [18, 16, 14, 13, 12]), 100);
            break;
        // 二级穿透查询区块
        case 'planAchievementTrend':
            title = '采购计划达成率趋势 - 折线图';
            html = `<canvas id="modalPlanAchievementTrendChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPlanAchievementTrendChart', '采购计划达成率', [88, 90, 92, 94, 94.2]), 100);
            break;
        case 'unplannedTrend':
            title = '计划外采购占比趋势 - 折线图';
            html = `<canvas id="modalUnplannedTrendChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalUnplannedTrendChart', '计划外采购占比', [18, 16, 14, 13, 12.5]), 100);
            break;
        case 'purchaseCycleTrend':
            title = '采购周期趋势 - 折线图';
            html = `<canvas id="modalPurchaseCycleTrendChart" height="300"></canvas>`;
            setTimeout(() => renderMultiLineChart('modalPurchaseCycleTrendChart', ['到货周期', '入库周期', '库存时间'], [[18, 17, 16.5, 16, 15.5], [3.5, 3.2, 3.0, 2.9, 2.8], [35, 33, 31, 30, 28.5]]), 100);
            break;
        case 'qualityCostTrend':
            title = '质量与成本趋势 - 折线图';
            html = `<canvas id="modalQualityCostTrendChart" height="300"></canvas>`;
            setTimeout(() => renderMultiLineChart('modalQualityCostTrendChart', ['质量合格率', '成本达成率'], [[96, 97, 97.5, 98, 98.7], [90, 92, 93, 94, 95.4]]), 100);
            break;
        case 'inventoryDaysTop5':
            title = '库存天数TOP5 - 水平直方图';
            html = `<canvas id="modalInventoryDaysTop5Chart" height="300"></canvas>`;
            setTimeout(() => renderBarChart('modalInventoryDaysTop5Chart', ['原材料A', '零部件B', '设备C', '辅料D', '包装物E'], [120, 95, 85, 75, 65]), 100);
            break;
        case 'inventoryTurnoverTrend':
            title = '库存周转趋势 - 折线图';
            html = `<canvas id="modalInventoryTurnoverTrendChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalInventoryTurnoverTrendChart', '库存周转率', [7.2, 7.5, 7.8, 8.2, 8.5]), 100);
            break;
        case 'materialPareto':
            title = '物料金额帕累托分析 - 组合图';
            html = `<canvas id="modalMaterialParetoChart" height="300"></canvas>`;
            setTimeout(() => renderParetoChart('modalMaterialParetoChart'), 100);
            break;
        case 'materialCategoryRatio':
            title = '物资类别金额占比 - 环形图';
            html = `<canvas id="modalMaterialCategoryRatioChart" height="300"></canvas>`;
            setTimeout(() => {
                createChart('modalMaterialCategoryRatioChart', {
                    type: 'doughnut',
                    data: {
                        labels: ['原材料', '零部件', '设备', '辅料', '包装物'],
                        datasets: [{
                            data: [35, 28, 20, 12, 5],
                            backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'],
                            borderWidth: 0,
                            hoverOffset: 4
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        cutout: '70%',
                        plugins: {
                            legend: { position: 'bottom' },
                            tooltip: {
                                callbacks: {
                                    label: function (context) {
                                        return `${context.label}: ${context.parsed}%`;
                                    }
                                }
                            }
                        }
                    }
                });
            }, 100);
            break;
        case 'materialCategoryDistribution':
            title = '物料类别分布 - 柱状图';
            html = `<canvas id="modalMaterialCategoryDistributionChart" height="300"></canvas>`;
            setTimeout(() => renderBarChart('modalMaterialCategoryDistributionChart', ['原材料', '零部件', '设备', '辅料', '包装物'], [450, 380, 280, 120, 26]), 100);
            break;
        case 'newMaterialTrend':
            title = '新增物料趋势 - 折线图';
            html = `<canvas id="modalNewMaterialTrendChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalNewMaterialTrendChart', '新增物料种数', [65, 72, 78, 85, 89]), 100);
            break;
        case 'supplierParetoAnalysis':
            title = '供应商金额帕累托分析 - 组合图';
            html = `<canvas id="modalSupplierParetoAnalysisChart" height="300"></canvas>`;
            setTimeout(() => renderParetoChart('modalSupplierParetoAnalysisChart'), 100);
            break;
        case 'supplierRiskTop5':
            title = '供应商风险TOP5 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>风险分析</b><br>
                    高风险供应商需要重点关注，及时制定风险应对方案。建议建立"一商一策"风险应对机制，包括备用供应商开发、安全库存策略、合同条款优化等措施。
                </div>
                <div class="bg-white rounded-lg p-4">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="border-b border-gray-200">
                                <th class="py-2 text-left">供应商名称</th>
                                <th class="py-2 text-center">风险类型</th>
                                <th class="py-2 text-center">风险评分</th>
                                <th class="py-2 text-center">影响物资</th>
                                <th class="py-2 text-center">应对措施</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="border-b border-gray-100">
                                <td class="py-2">供应商A</td>
                                <td class="py-2 text-center">交付风险</td>
                                <td class="py-2 text-center text-danger">高风险</td>
                                <td class="py-2 text-center">关键零部件</td>
                                <td class="py-2 text-center">开发备用供应商</td>
                            </tr>
                            <tr class="border-b border-gray-100">
                                <td class="py-2">供应商B</td>
                                <td class="py-2 text-center">质量风险</td>
                                <td class="py-2 text-center text-warning">中风险</td>
                                <td class="py-2 text-center">原材料</td>
                                <td class="py-2 text-center">加强质量管控</td>
                            </tr>
                            <tr class="border-b border-gray-100">
                                <td class="py-2">供应商C</td>
                                <td class="py-2 text-center">财务风险</td>
                                <td class="py-2 text-center text-warning">中风险</td>
                                <td class="py-2 text-center">设备</td>
                                <td class="py-2 text-center">监控财务状况</td>
                            </tr>
                            <tr class="border-b border-gray-100">
                                <td class="py-2">供应商D</td>
                                <td class="py-2 text-center">交付风险</td>
                                <td class="py-2 text-center text-warning">中风险</td>
                                <td class="py-2 text-center">辅料</td>
                                <td class="py-2 text-center">建立安全库存</td>
                            </tr>
                            <tr>
                                <td class="py-2">供应商E</td>
                                <td class="py-2 text-center">质量风险</td>
                                <td class="py-2 text-center text-warning">中风险</td>
                                <td class="py-2 text-center">包装物</td>
                                <td class="py-2 text-center">加强检验</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            `;
            break;
        case 'modelAmountTop5':
            title = '型号金额TOP5 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>分析说明</b><br>
                    型号金额TOP5展示了不同维度下金额最高的5个物资型号，帮助识别高价值物资，便于重点管理和优化采购策略。通过多维度对比可以发现型号在不同业务环节的表现差异。
                </div>
                
                <!-- Tab切换选项 -->
                <div class="flex flex-wrap gap-2 mb-4">
                    <button class="modal-model-tab-btn active px-3 py-1.5 text-sm rounded-lg transition-colors" data-tab="inventory">
                        按库存
                    </button>
                    <button class="modal-model-tab-btn px-3 py-1.5 text-sm rounded-lg transition-colors" data-tab="demand">
                        按需求
                    </button>
                    <button class="modal-model-tab-btn px-3 py-1.5 text-sm rounded-lg transition-colors" data-tab="purchase">
                        按采购
                    </button>
                    <button class="modal-model-tab-btn px-3 py-1.5 text-sm rounded-lg transition-colors" data-tab="arrival">
                        按到货
                    </button>
                    <button class="modal-model-tab-btn px-3 py-1.5 text-sm rounded-lg transition-colors" data-tab="warehouse">
                        按入库
                    </button>
                    <button class="modal-model-tab-btn px-3 py-1.5 text-sm rounded-lg transition-colors" data-tab="outbound">
                        按出库
                    </button>
                </div>
                
                <div class="h-64">
                    <canvas id="modalModelAmountTop5Chart"></canvas>
                </div>
                
                <div class="mt-4 p-3 bg-light rounded text-sm text-gray-700">
                    <b>管理建议</b><br>
                    1. 高价值型号应建立专项管理制度，包括安全库存、定期盘点等<br>
                    2. 重点关注型号在不同环节的金额差异，识别供应链瓶颈<br>
                    3. 对TOP5型号建立供应商备选方案，降低供应风险
                </div>
            `;
            setTimeout(() => {
                // 定义模态框中的型号数据
                const modalModelData = {
                    inventory: { title: '库存金额', data: [280, 220, 180, 150, 120] },
                    demand: { title: '需求金额', data: [320, 260, 200, 170, 140] },
                    purchase: { title: '采购金额', data: [300, 240, 190, 160, 130] },
                    arrival: { title: '到货金额', data: [290, 230, 185, 155, 125] },
                    warehouse: { title: '入库金额', data: [285, 225, 182, 152, 122] },
                    outbound: { title: '出库金额', data: [275, 215, 175, 145, 115] }
                };

                const labels = ['型号A-001', '型号B-002', '型号C-003', '型号D-004', '型号E-005'];
                const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'];

                // 更新模态框图表函数
                function updateModalModelChart(tabType) {
                    const data = modalModelData[tabType];
                    createChart('modalModelAmountTop5Chart', {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: [{
                                label: `${data.title}(万元)`,
                                data: data.data,
                                backgroundColor: colors,
                                borderWidth: 0,
                                borderRadius: 4
                            }]
                        },
                        options: {
                            indexAxis: 'y',
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: { display: false },
                                tooltip: {
                                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                    titleColor: '#1D2129',
                                    bodyColor: '#4E5969',
                                    borderColor: 'rgba(22, 93, 255, 0.2)',
                                    borderWidth: 1,
                                    padding: 12,
                                    boxPadding: 6,
                                    usePointStyle: true,
                                    callbacks: {
                                        label: function (context) {
                                            return `${context.dataset.label}: ${context.raw}万元`;
                                        }
                                    }
                                }
                            },
                            scales: {
                                x: {
                                    grid: { color: 'rgba(0, 0, 0, 0.05)' },
                                    ticks: { color: '#86909C', font: { size: 12 } },
                                    title: { display: true, text: `${data.title}(万元)`, color: '#86909C', font: { size: 12 } }
                                },
                                y: {
                                    grid: { display: false },
                                    ticks: { color: '#86909C', font: { size: 11 } }
                                }
                            }
                        }
                    });
                }

                // 初始化模态框图表
                updateModalModelChart('inventory');

                // 绑定模态框Tab切换事件
                const modalModelTabButtons = document.querySelectorAll('.modal-model-tab-btn');
                modalModelTabButtons.forEach(button => {
                    button.addEventListener('click', function () {
                        modalModelTabButtons.forEach(btn => btn.classList.remove('active'));
                        this.classList.add('active');
                        const tabType = this.getAttribute('data-tab');
                        updateModalModelChart(tabType);
                    });
                });
            }, 100);
            break;
        default:
            title = '详细分析';
            html = '<div>暂无详细内容</div>';
    }
    modalTitle.innerText = title;
    modalContent.innerHTML = html;
}

// =====================
// 4. 图表渲染入口（Chart.js）
// =====================
// 折线图示例
function renderLineChart(canvasId, label, data, labels) {
    createChart(canvasId, {
        type: 'line',
        data: {
            labels: labels || ['一月', '二月', '三月', '四月', '五月'],
            datasets: [{
                label: label,
                data: data,
                borderColor: '#165DFF',
                backgroundColor: 'rgba(22,93,255,0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: true } }
        }
    });
}
// 多折线图
function renderMultiLineChart(canvasId, labelsArr, dataArr, xLabels) {
    const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F'];
    createChart(canvasId, {
        type: 'line',
        data: {
            labels: xLabels || ['一月', '二月', '三月', '四月', '五月'],
            datasets: labelsArr.map((label, i) => ({
                label: label,
                data: dataArr[i],
                borderColor: colors[i % colors.length],
                backgroundColor: colors[i % colors.length] + '22',
                fill: false,
                tension: 0.4
            }))
        },
        options: {
            responsive: true,
            plugins: { legend: { display: true } }
        }
    });
}
// 柱状图
function renderBarChart(canvasId, labels, data) {
    createChart(canvasId, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '数值',
                data: data,
                backgroundColor: '#165DFF',
            }]
        },
        options: { responsive: true }
    });
}
// 帕累托组合图
function renderParetoChart(canvasId) {
    createChart(canvasId, {
        type: 'bar',
        data: {
            labels: ['类型A', '类型B', '类型C', '类型D', '类型E'],
            datasets: [
                {
                    label: '供货金额',
                    data: [100, 80, 60, 40, 20],
                    backgroundColor: '#165DFF',
                    yAxisID: 'y',
                },
                {
                    label: '累计占比',
                    data: [20, 40, 65, 85, 100],
                    type: 'line',
                    borderColor: '#FF7D00',
                    backgroundColor: 'rgba(255,125,0,0.1)',
                    yAxisID: 'y1',
                }
            ]
        },
        options: {
            responsive: true,
            scales: {
                y: { beginAtZero: true, position: 'left', title: { display: true, text: '金额' } },
                y1: { beginAtZero: true, position: 'right', title: { display: true, text: '累计占比(%)' }, grid: { drawOnChartArea: false } }
            }
        }
    });
}

// =====================
// 5. 静态数据结构示例
// =====================
// 如需对接真实数据，可在此定义数据结构
// const kpiData = { ... };
// 当前未直接使用，已注释避免linter报错

// =====================
// 6. 页面加载后可自动渲染首页主要图表
// =====================
window.onload = function () {
    // 清理所有现有的Chart实例，避免重复创建
    Object.keys(chartInstances).forEach(canvasId => {
        destroyChart(canvasId);
    });

    // 侧边栏切换功能
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');
    const toggleSidebar = document.getElementById('toggleSidebar');
    if (sidebar && mainContent && toggleSidebar) {
        toggleSidebar.onclick = function () {
            // 切换侧边栏宽度
            sidebar.classList.toggle('w-64');
            sidebar.classList.toggle('w-16');
            // 切换主内容区左边距
            mainContent.classList.toggle('pl-64');
            mainContent.classList.toggle('pl-16');
            // 切换侧边栏内文字显示
            sidebar.classList.toggle('sidebar-collapsed');
        };
    }

    // 物资分析相关图表渲染
    // 计划管理图表
    if (document.getElementById('planAchievementChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const planData = [88, 90, 92, 94, 94.2];
        renderLineChart('planAchievementChart', '采购计划达成率', planData, years);
    }
    if (document.getElementById('unplannedRatioChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const unplannedData = [18, 16, 14, 13, 12.5];
        renderLineChart('unplannedRatioChart', '计划外采购占比', unplannedData, years);
    }
    if (document.getElementById('purchaseCycleChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const arrivalData = [18, 17, 16.5, 16, 15.5];
        const warehouseData = [3.5, 3.2, 3.0, 2.9, 2.8];
        const inventoryData = [35, 33, 31, 30, 28.5];
        renderMultiLineChart('purchaseCycleChart', ['到货周期', '入库周期', '库存时间'], [arrivalData, warehouseData, inventoryData], years);
    }
    if (document.getElementById('qualityCostChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const qualityData = [96, 97, 97.5, 98, 98.7];
        const costData = [90, 92, 93, 94, 95.4];
        renderMultiLineChart('qualityCostChart', ['质量合格率', '成本达成率'], [qualityData, costData], years);
    }

    // 供应商供货分析图表
    if (document.getElementById('rfmTrendChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const rfmData = [3.5, 3.8, 3.6, 3.9, 3.7];
        renderLineChart('rfmTrendChart', 'RFM总分平均值', rfmData, years);
    }
    if (document.getElementById('supplyTrendChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const data1 = [350, 370, 360, 385, 375]; // 供货金额(万元)
        const data2 = [80, 90, 85, 95, 90];      // 单次供货金额(万元)
        renderMultiLineChart('supplyTrendChart', ['供货金额(万元)', '单次供货金额(万元)'], [data1, data2], years);
    }

    // 供应商结构分析图表
    if (document.getElementById('supplierTypeChart')) {
        createChart('supplierTypeChart', {
            type: 'doughnut',
            data: {
                labels: ['重要价值供应商', '重要保持供应商', '重要发展供应商', '重要挽留供应商', '一般价值供应商', '低价值供应商'],
                datasets: [{
                    data: [28.5, 22.3, 18.7, 15.2, 8.8, 6.5],
                    backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C', '#C9CDD4'],
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                const label = context.label || '';
                                const value = context.parsed || 0;
                                return `${label}: ${value}%`;
                            }
                        }
                    }
                },
                animation: {
                    animateRotate: true,
                    animateScale: true
                },
                onHover: (event, chartElement) => {
                    event.native.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
                }
            }
        });
        // 点击环形图弹出二级穿透查询弹窗
        const supplierTypeChartDom = document.getElementById('supplierTypeChart');
        if (supplierTypeChartDom) {
            supplierTypeChartDom.onclick = function () {
                showDetail('supplierCategory');
            };
        }
    }
    if (document.getElementById('supplierTypeParetoChart')) {
        createChart('supplierTypeParetoChart', {
            type: 'bar',
            data: {
                labels: ['重要价值供应商', '重要保持供应商', '重要发展供应商', '重要挽留供应商', '一般价值供应商', '低价值供应商'],
                datasets: [
                    {
                        label: '供货金额(万元)',
                        data: [320, 240, 180, 140, 100, 80],
                        backgroundColor: '#165DFF',
                        borderWidth: 0,
                        yAxisID: 'y'
                    },
                    {
                        label: '累计供货占比',
                        data: [28.5, 46.8, 65.3, 80.1, 90.9, 100],
                        borderColor: '#FF7D00',
                        backgroundColor: 'rgba(255, 125, 0, 0.2)',
                        borderWidth: 2,
                        pointBackgroundColor: '#FF7D00',
                        pointRadius: 4,
                        type: 'line',
                        tension: 0.4,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 12 } }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                if (context.dataset.label === '供货金额(万元)') {
                                    return `${context.dataset.label}: ${context.raw}万元`;
                                } else {
                                    return `${context.dataset.label}: ${context.raw}%`;
                                }
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: '#86909C', font: { size: 10 }, autoSkip: false, maxRotation: 45, minRotation: 45 }
                    },
                    y: {
                        type: 'linear', display: true, position: 'left',
                        title: { display: true, text: '供货金额(万元)', color: '#86909C', font: { size: 12 } },
                        grid: { color: 'rgba(0, 0, 0, 0.05)' },
                        ticks: { color: '#86909C' }
                    },
                    y1: {
                        type: 'linear', display: true, position: 'right',
                        title: { display: true, text: '累计供货占比(%)', color: '#86909C', font: { size: 12 } },
                        grid: { drawOnChartArea: false },
                        ticks: { color: '#86909C', callback: function (value) { return value + '%'; } },
                        min: 0,
                        max: 100
                    }
                }
            }
        });
    }

    // 库存运营图表
    if (document.getElementById('inventoryDaysChart')) {
        const labels = ['原材料A', '零部件B', '设备C', '辅料D', '包装物E'];
        const data = [120, 95, 85, 75, 65];
        renderBarChart('inventoryDaysChart', labels, data);
    }
    if (document.getElementById('inventoryTurnoverChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const turnoverData = [7.2, 7.5, 7.8, 8.2, 8.5];
        renderLineChart('inventoryTurnoverChart', '库存周转率', turnoverData, years);
    }

    // 新增物料趋势图表
    if (document.getElementById('newMaterialTrendChart')) {
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const newMaterialData = [65, 72, 78, 85, 89];
        renderLineChart('newMaterialTrendChart', '新增物料种数', newMaterialData, years);
    }

    // 型号金额TOP5图表
    if (document.getElementById('modelAmountTop5Chart')) {
        // 定义不同维度的型号金额TOP5数据
        const modelTop5Data = {
            inventory: {
                title: '库存金额',
                labels: ['型号A-001', '型号B-002', '型号C-003', '型号D-004', '型号E-005'],
                data: [280, 220, 180, 150, 120],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            demand: {
                title: '需求金额',
                labels: ['型号A-001', '型号B-002', '型号C-003', '型号D-004', '型号E-005'],
                data: [320, 260, 200, 170, 140],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            purchase: {
                title: '采购金额',
                labels: ['型号A-001', '型号B-002', '型号C-003', '型号D-004', '型号E-005'],
                data: [300, 240, 190, 160, 130],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            arrival: {
                title: '到货金额',
                labels: ['型号A-001', '型号B-002', '型号C-003', '型号D-004', '型号E-005'],
                data: [290, 230, 185, 155, 125],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            warehouse: {
                title: '入库金额',
                labels: ['型号A-001', '型号B-002', '型号C-003', '型号D-004', '型号E-005'],
                data: [285, 225, 182, 152, 122],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            outbound: {
                title: '出库金额',
                labels: ['型号A-001', '型号B-002', '型号C-003', '型号D-004', '型号E-005'],
                data: [275, 215, 175, 145, 115],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            }
        };

        // 更新型号金额TOP5图表
        function updateModelTop5Chart(tabType) {
            const data = modelTop5Data[tabType];

            createChart('modelAmountTop5Chart', {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: `${data.title}(万元)`,
                        data: data.data,
                        backgroundColor: data.colors,
                        borderWidth: 0,
                        borderRadius: 4
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: 'rgba(255, 255, 255, 0.9)',
                            titleColor: '#1D2129',
                            bodyColor: '#4E5969',
                            borderColor: 'rgba(22, 93, 255, 0.2)',
                            borderWidth: 1,
                            padding: 12,
                            boxPadding: 6,
                            usePointStyle: true,
                            callbacks: {
                                label: function (context) {
                                    return `${context.dataset.label}: ${context.raw}万元`;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: { color: 'rgba(0, 0, 0, 0.05)' },
                            ticks: { color: '#86909C', font: { size: 12 } },
                            title: { display: true, text: `${data.title}(万元)`, color: '#86909C', font: { size: 12 } }
                        },
                        y: {
                            grid: { display: false },
                            ticks: { color: '#86909C', font: { size: 11 } }
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeInOutQuart'
                    }
                }
            });
        }

        // 初始化图表（默认按库存）
        updateModelTop5Chart('inventory');

        // 绑定Tab切换事件
        const modelTabButtons = document.querySelectorAll('.model-tab-btn');
        modelTabButtons.forEach(button => {
            button.addEventListener('click', function () {
                // 移除所有active类
                modelTabButtons.forEach(btn => btn.classList.remove('active'));
                // 添加active类到当前按钮
                this.classList.add('active');
                // 更新图表
                const tabType = this.getAttribute('data-tab');
                updateModelTop5Chart(tabType);
            });
        });

        // 点击图表弹出二级穿透查询弹窗
        const modelTop5ChartDom = document.getElementById('modelAmountTop5Chart');
        if (modelTop5ChartDom) {
            modelTop5ChartDom.onclick = function () {
                showDetail('modelAmountTop5');
            };
        }
    }

    // 物资类别图表
    if (document.getElementById('materialCategoryChart')) {
        // 定义不同维度的物资类别数据
        const categoryData = {
            inventory: {
                title: '库存金额',
                data: [35, 28, 20, 12, 5],
                labels: ['原材料', '零部件', '设备', '辅料', '包装物'],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            demand: {
                title: '需求金额',
                data: [40, 30, 18, 8, 4],
                labels: ['原材料', '零部件', '设备', '辅料', '包装物'],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            purchase: {
                title: '采购金额',
                data: [38, 29, 19, 10, 4],
                labels: ['原材料', '零部件', '设备', '辅料', '包装物'],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            arrival: {
                title: '到货金额',
                data: [36, 27, 18, 11, 8],
                labels: ['原材料', '零部件', '设备', '辅料', '包装物'],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            warehouse: {
                title: '入库金额',
                data: [34, 26, 17, 12, 11],
                labels: ['原材料', '零部件', '设备', '辅料', '包装物'],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            },
            outbound: {
                title: '出库金额',
                data: [32, 25, 16, 13, 14],
                labels: ['原材料', '零部件', '设备', '辅料', '包装物'],
                colors: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C']
            }
        };

        // 生成图例HTML
        function generateLegend(data) {
            const legendContainer = document.getElementById('materialCategoryLegend');
            if (!legendContainer) return;

            let legendHTML = '';
            data.labels.forEach((label, index) => {
                const percentage = data.data[index];
                const color = data.colors[index];
                legendHTML += `
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-2">
                            <div class="w-3 h-3 rounded-full" style="background-color: ${color}"></div>
                            <span class="text-sm text-gray-700">${label}</span>
                        </div>
                        <span class="text-sm font-medium text-gray-900">${percentage}%</span>
                    </div>
                `;
            });
            legendContainer.innerHTML = legendHTML;
        }

        // 更新物资类别图表
        function updateCategoryChart(tabType) {
            const data = categoryData[tabType];

            createChart('materialCategoryChart', {
                type: 'doughnut',
                data: {
                    labels: data.labels,
                    datasets: [{
                        data: data.data,
                        backgroundColor: data.colors,
                        borderWidth: 0,
                        hoverOffset: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '70%',
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: 'rgba(255, 255, 255, 0.9)',
                            titleColor: '#1D2129',
                            bodyColor: '#4E5969',
                            borderColor: 'rgba(22, 93, 255, 0.2)',
                            borderWidth: 1,
                            padding: 12,
                            boxPadding: 6,
                            usePointStyle: true,
                            callbacks: {
                                label: function (context) {
                                    const label = context.label || '';
                                    const value = context.parsed || 0;
                                    return `${label}: ${value}%`;
                                }
                            }
                        }
                    },
                    animation: {
                        animateRotate: true,
                        animateScale: true
                    },
                    onHover: (event, chartElement) => {
                        event.native.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
                    }
                }
            });

            // 生成图例
            generateLegend(data);
        }

        // 初始化图表（默认按库存）
        updateCategoryChart('inventory');

        // 绑定Tab切换事件
        const categoryTabButtons = document.querySelectorAll('.category-tab-btn');
        categoryTabButtons.forEach(button => {
            button.addEventListener('click', function () {
                // 移除所有active类
                categoryTabButtons.forEach(btn => btn.classList.remove('active'));
                // 添加active类到当前按钮
                this.classList.add('active');
                // 更新图表
                const tabType = this.getAttribute('data-tab');
                updateCategoryChart(tabType);
            });
        });

        // 点击环形图弹出二级穿透查询弹窗
        const materialCategoryChartDom = document.getElementById('materialCategoryChart');
        if (materialCategoryChartDom) {
            materialCategoryChartDom.onclick = function () {
                showDetail('materialCategoryRatio');
            };
        }
    }

    // 物料金额帕累托分析Tab切换功能
    if (document.getElementById('materialParetoChart')) {
        // 定义不同维度的帕累托数据
        const paretoData = {
            inventory: {
                title: '库存金额',
                data: [120, 100, 80, 60, 40],
                cumData: [20, 40, 65, 85, 100]
            },
            demand: {
                title: '需求金额',
                data: [150, 120, 90, 70, 50],
                cumData: [20, 40, 65, 85, 100]
            },
            purchase: {
                title: '采购金额',
                data: [140, 110, 85, 65, 45],
                cumData: [20, 40, 65, 85, 100]
            },
            arrival: {
                title: '到货金额',
                data: [135, 105, 80, 60, 40],
                cumData: [20, 40, 65, 85, 100]
            },
            warehouse: {
                title: '入库金额',
                data: [130, 100, 75, 55, 35],
                cumData: [20, 40, 65, 85, 100]
            },
            outbound: {
                title: '出库金额',
                data: [125, 95, 70, 50, 30],
                cumData: [20, 40, 65, 85, 100]
            }
        };

        // 初始化帕累托图表（默认按库存）
        function updateParetoChart(tabType) {
            const data = paretoData[tabType];
            const labels = ['物资A', '物资B', '物资C', '物资D', '物资E'];

            createChart('materialParetoChart', {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: `${data.title}(万元)`,
                            data: data.data,
                            backgroundColor: '#165DFF',
                            borderWidth: 0,
                            yAxisID: 'y'
                        },
                        {
                            label: '累计占比',
                            data: data.cumData,
                            borderColor: '#FF7D00',
                            backgroundColor: 'rgba(255, 125, 0, 0.2)',
                            borderWidth: 2,
                            pointBackgroundColor: '#FF7D00',
                            pointRadius: 4,
                            type: 'line',
                            tension: 0.4,
                            yAxisID: 'y1'
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 12 } }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(255, 255, 255, 0.9)',
                            titleColor: '#1D2129',
                            bodyColor: '#4E5969',
                            borderColor: 'rgba(22, 93, 255, 0.2)',
                            borderWidth: 1,
                            padding: 12,
                            boxPadding: 6,
                            usePointStyle: true,
                            callbacks: {
                                label: function (context) {
                                    if (context.dataset.label.includes('金额')) {
                                        return `${context.dataset.label}: ${context.raw}万元`;
                                    } else {
                                        return `${context.dataset.label}: ${context.raw}%`;
                                    }
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: { display: false },
                            ticks: { color: '#86909C', font: { size: 10 } }
                        },
                        y: {
                            type: 'linear', display: true, position: 'left',
                            title: { display: true, text: `${data.title}(万元)`, color: '#86909C', font: { size: 12 } },
                            grid: { color: 'rgba(0, 0, 0, 0.05)' },
                            ticks: { color: '#86909C' }
                        },
                        y1: {
                            type: 'linear', display: true, position: 'right',
                            title: { display: true, text: '累计占比(%)', color: '#86909C', font: { size: 12 } },
                            grid: { drawOnChartArea: false },
                            ticks: { color: '#86909C', callback: function (value) { return value + '%'; } },
                            min: 0,
                            max: 100
                        }
                    }
                }
            });
        }

        // 初始化图表
        updateParetoChart('inventory');

        // 绑定Tab切换事件
        const tabButtons = document.querySelectorAll('.tab-btn');
        tabButtons.forEach(button => {
            button.addEventListener('click', function () {
                // 移除所有active类
                tabButtons.forEach(btn => btn.classList.remove('active'));
                // 添加active类到当前按钮
                this.classList.add('active');
                // 更新图表
                const tabType = this.getAttribute('data-tab');
                updateParetoChart(tabType);
            });
        });
    }

    // 供应商管理图表
    if (document.getElementById('supplierParetoChart')) {
        const labels = ['供应商A', '供应商B', '供应商C', '供应商D', '供应商E', '供应商F', '供应商G', '供应商H', '供应商I', '供应商J'];
        const amounts = [120, 110, 90, 80, 70, 60, 50, 40, 30, 20];
        const cumPercents = [12, 23, 32, 40, 47, 53, 58, 62, 65, 67];
        createChart('supplierParetoChart', {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: '供货金额(万元)',
                        data: amounts,
                        backgroundColor: '#0FC6C2',
                        borderWidth: 0,
                        yAxisID: 'y'
                    },
                    {
                        label: '累计供货占比',
                        data: cumPercents,
                        borderColor: '#FF7D00',
                        backgroundColor: 'rgba(255, 125, 0, 0.2)',
                        borderWidth: 2,
                        pointBackgroundColor: '#FF7D00',
                        pointRadius: 4,
                        type: 'line',
                        tension: 0.4,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 12 } }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                if (context.dataset.label === '供货金额(万元)') {
                                    return `${context.dataset.label}: ${context.raw}万元`;
                                } else {
                                    return `${context.dataset.label}: ${context.raw}%`;
                                }
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: '#86909C', font: { size: 10 }, autoSkip: false, maxRotation: 45, minRotation: 45 }
                    },
                    y: {
                        type: 'linear', display: true, position: 'left',
                        title: { display: true, text: '供货金额(万元)', color: '#86909C', font: { size: 12 } },
                        grid: { color: 'rgba(0, 0, 0, 0.05)' },
                        ticks: { color: '#86909C' }
                    },
                    y1: {
                        type: 'linear', display: true, position: 'right',
                        title: { display: true, text: '累计供货占比(%)', color: '#86909C', font: { size: 12 } },
                        grid: { drawOnChartArea: false },
                        ticks: { color: '#86909C', callback: function (value) { return value + '%'; } },
                        min: 0,
                        max: 100
                    }
                }
            }
        });
    }
}; 